﻿//Copyright md bravo - feel free to modify this code in any way - just leave this notice ;)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ShareCDN.Engine.Web
{
	public class DownloadHandler : System.Web.IHttpHandler
	{
		public bool IsReusable
		{
			get { return true; }
		}

		public void ProcessRequest(HttpContext context)
		{
			var path = context.Request.Path;
			var hashKey = context.Request.QueryString[0];
			var handler = ShareCDN.Engine.Runtime.Manager.GetHandle(hashKey);
			if (handler != null)
			{
				using (handler)
				{
					var buffer = new byte[1024];
					context.Response.ContentType = handler.ContentType;
					if (handler.FileName != null)
					{
						//todo some content disposition
					}
					int count = 0;
					while ((count = handler.Stream.Read(buffer, 0, 1024)) > 0)
					{
						context.Response.Flush();
						context.Response.OutputStream.Write(buffer, 0, count);
					}
				}
				context.Response.End();
			}
			else
			{
				context.Response.Write("File does not exist");

				context.Response.StatusCode = 404;

				context.Response.End();
			}


		}
	}
}